//
//  CTRequestUtil.m
//  ConstellationTalk_0.1
//
//  Created by riley on 15/4/21.
//  Copyright (c) 2015年 riley chu. All rights reserved.
//

#import "CTRequestUtil.h"
#import "CTHeader.h"
#import "CTDebugManager.h"
#import "CTTextManager.h"

#import "EGOImageLoader.h"
#import "SDWebImageManager.h"

static CTRequestUtil * requestUtil = nil;

@interface CTRequestUtil ()<EGOImageLoaderObserver>
{
    imgRequestCompletionSuccessBlock  completionBolck;
}
@end


@implementation CTRequestUtil

- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

+(CTRequestUtil *)shareInstance
{
    @synchronized (self)
    {
        if (requestUtil == nil)
        {
            requestUtil = [[CTRequestUtil alloc] init];
        }
    }
    return requestUtil;
}


+(void)sendAsyGetRequest:(NSString *)url
               withParam:(NSMutableDictionary *)param
withCompletionSuccessHandler:(downloadCompletionSuccessBlock)successBlock
       withFailedHandler:(downloadFailedBlock)failedBlock
{
    
    NSError * err;
    
    if(url == nil){
        failedBlock(err);
        return;
    }

    url = [url stringByAppendingString:[self parserGetDataForHttpBody:param]];
    
    NSURL *myURL = [NSURL URLWithString:url];
    
   
    NSURLRequest *urlRequest = [NSURLRequest
                                requestWithURL:myURL
                                cachePolicy:
                                NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                timeoutInterval:CT_HEADER_REQUEST_TIMEOUT_INTERVAL];
    
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    
    
    
    [NSURLConnection sendAsynchronousRequest:urlRequest
                                       queue:queue
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                            
                               
//                               [timeOutTimer invalidate];
//                               timeOutTimer = nil;
                              
                               if( [response isKindOfClass:[NSHTTPURLResponse class]] ){
                                   NSHTTPURLResponse *responseCopy = (NSHTTPURLResponse *)response;
                                   NSInteger statusCode = responseCopy.statusCode;
                                   if(statusCode == 200){
                                
                                       
                                       if ([data length] == 0) {
                                           [CTDebugManager showDebugLogInfo:@"数据为空!!"];
                                           failedBlock(error);
                                       }
                                       else
                                       {
                                           [CTDebugManager showDebugLogInfo:@"请求成功!!"];
                                           successBlock(data);
                                       }
                                   }else{
                                       [CTDebugManager showErrorLogInfo:@"请求失败!!"];
                                       failedBlock(error);
                
                                   }
                               }
                               
                           }];
 
}



+(void)sendAsyPostRequest:(NSString *)url withParam:(NSMutableDictionary *)param withCompletionSuccessHandler:(downloadCompletionSuccessBlock)successBlock withFailedHandler:(downloadFailedBlock)failedBlock
{
    NSError * err;
    if(url == nil){
        failedBlock(err);
        return;
    }
    if(param == nil || param.count == 0){
        failedBlock(err);
        return;
    }
    
    //配置url
    NSURL *myURL = [NSURL URLWithString:url];
    NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:CT_HEADER_REQUEST_TIMEOUT_INTERVAL];
    
    //设置type
    [urlRequest setHTTPMethod:@"POST"];
    
    [urlRequest setTimeoutInterval:CT_HEADER_REQUEST_TIMEOUT_INTERVAL];
   
     [urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
    //设置header
    if ((NSString *)[param objectForKey:@"openid"] != nil) {
        NSString *contentType = [NSString stringWithFormat:@"%@",[NSString stringWithFormat:@"%@",(NSString *)[param objectForKey:@"openid"]]];
        [urlRequest setValue:contentType forHTTPHeaderField:@"openid"];
        [param removeObjectForKey:@"openid"];
    }else{
        if ( (NSString *)[param objectForKey:@"token"] != nil) {
            NSString *contentType = [NSString stringWithFormat:@"%@",[NSString stringWithFormat:@"%@",(NSString *)[param objectForKey:@"token"]]];
            [urlRequest setValue:contentType forHTTPHeaderField:@"token"];
            [param removeObjectForKey:@"token"];
        }
    }
    
    //设置body
    NSData *data = [self parserPostDataForHttpBody:param];
    if (data.length != 0)[urlRequest setHTTPBody:data];
    
    
    
//    //自定义时间超时
//    [NSTimer timerWithTimeInterval:CT_HEADER_REQUEST_TIMEOUT_INTERVAL target:self selector:@selector(handleTimerOut) userInfo:nil repeats:NO];
    
    
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [NSURLConnection sendAsynchronousRequest:urlRequest
                                       queue:queue
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                               
                               
                               if( [response isKindOfClass:[NSHTTPURLResponse class]] ){
                                   NSHTTPURLResponse *responseCopy = (NSHTTPURLResponse *)response;
                                   NSInteger statusCode = responseCopy.statusCode;
                                   
//                                   [timeOutTimer invalidate];
//                                   timeOutTimer = nil;
                                   
                                   
                                   if(statusCode == 200){
                                       
                                       if (data&&[data length] == 0) {
                                           [CTDebugManager showDebugLogInfo:@"数据为空!!"];
                                           failedBlock(error);
                                       }
                                       else
                                       {
                                           [CTDebugManager showDebugLogInfo:@"请求成功!!"];
                                           successBlock(data);
                                       }
                                   }else{
                                       [CTDebugManager showErrorLogInfo:@"请求失败!!"];
                                       failedBlock(error);
                                      
                                   }
                               }
                               
                           }];
    
    
}


+(UIImage *)requestImageWithUrl:(NSString *)url
{
   
    if([[CTTextManager shareInstance] isBlankString:url]){
        return nil;
    }
    
    UIImage * img = [[EGOImageLoader sharedImageLoader] imageForURL:[NSURL URLWithString:url] shouldLoadWithObserver:nil];
    return img;
}


+(void)requestImgWithUrl:(NSString *)url withCompletionSuccessHandler:(imgRequestCompletionSuccessBlock)successBlock withFailedHandler:(imgRequestFailedBlock)failedBlock
{
    NSError * err;
    
    if([[CTTextManager shareInstance] isBlankString:url]){
        failedBlock(err);
        return;
    }
    
    
    __block UIImage * img;
    
   
    [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:url] options:SDWebImageDelayPlaceholder progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        img = image;
        dispatch_async(dispatch_get_main_queue(), ^{
            successBlock (img);
        });
    }];
}





#pragma mark - parser -

+(NSData *)parserPostDataForHttpBody:(NSMutableDictionary *)dic
{
    NSData * data;
    
    if (dic.count == 0 || dic == nil){
        [CTDebugManager showErrorLogInfo:@"post数据参数为空!!"];
        return data;}
    
    @try {
        NSString * bodyStr = [NSString stringWithFormat:@""];
        NSArray * keysArray = [dic allKeys];
        for (int i=0; i<keysArray.count; i ++){
            NSString * keyStr;
            NSString * valueStr;
            if (i == 0) {
                keyStr = (NSString *)[keysArray objectAtIndex:i];
                valueStr = (NSString *)[dic objectForKey:keyStr];
                bodyStr = [bodyStr stringByAppendingString:[NSString stringWithFormat:@"%@=%@",keyStr,valueStr]];
            }
            else
            {
                keyStr = (NSString *)[keysArray objectAtIndex:i];
                valueStr = (NSString *)[dic objectForKey:keyStr];
                bodyStr = [bodyStr stringByAppendingString:[NSString stringWithFormat:@"&%@=%@",keyStr,valueStr]];
            }
        }
        
        bodyStr = [bodyStr stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
        
        data = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    }
    @catch (NSException *exception) {
        [CTDebugManager showErrorLogInfo:@"解析post数据失败!!"];
    }
    
    
    return data;
}

+(NSString *)parserGetDataForHttpBody:(NSMutableDictionary *)dic
{
    NSString * bodyStr;
    
    @try {
        bodyStr = [NSString stringWithFormat:@""];
        NSArray * keysArray = [dic allKeys];
        for (int i=0; i<keysArray.count; i ++){
            NSString * keyStr;
            NSString * valueStr;
            if (i == 0) {
                keyStr = (NSString *)[keysArray objectAtIndex:i];
                valueStr = (NSString *)[dic objectForKey:keyStr];
                valueStr =  (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)valueStr, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]",  kCFStringEncodingUTF8 ));
                bodyStr = [bodyStr stringByAppendingString:[NSString stringWithFormat:@"?%@=%@",keyStr,valueStr]];
            }
            else
            {
                keyStr = (NSString *)[keysArray objectAtIndex:i];
                valueStr = (NSString *)[dic objectForKey:keyStr];
                valueStr =  (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)valueStr, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]",  kCFStringEncodingUTF8 ));
                bodyStr = [bodyStr stringByAppendingString:[NSString stringWithFormat:@"&%@=%@",keyStr,valueStr]];
            }
        }
       
    }
    @catch (NSException *exception) {
        [CTDebugManager showErrorLogInfo:@"解析get数据失败!!"];
    }
 
    return bodyStr;
}


@end
